package com.strongbj.iot.devices.hr.response.handle;

import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.hr.message.HRMessage;
import com.strongbj.iot.devices.hr.message.MQMessageOfHR;
import com.strongbj.iot.devices.hr.response.entity.BootInfoEntity;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;

/**
 * 开机信息处理类【设置设备工作于用户预先配置好的模式】
 * 
 * @author Pingfan
 *
 */
public class HRBootInfoHandle implements IMessageHandle<HRMessage, Object> {
	protected static Logger logger = LogManager.getLogger(HRBootInfoHandle.class.getName());
	protected TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	protected static final String ACTION_CODE = "collect001";
	
	public HRBootInfoHandle(String doorDirection) {
		super();
	}
	
	@Override
	public boolean isHandle(HRMessage t) {
		if (t.getCommand() == 0x01) { // 开机信息命令类型为0x01
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, HRMessage t) {
		// 取门禁ip
		InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
		String devIp = insocket.getAddress().getHostAddress();

		// 拼接发送消息
		BootInfoEntity bootInfo = new BootInfoEntity();
		bootInfo.setDevIp(devIp);
		bootInfo.setCommand(t.getCommand());
		
		// 获取当前系统时间代替指令中的时间
		SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		bootInfo.setCurrentTime(formatter.format(new Date()));
		
		// 开机信息data段固定8个字节,依次为时间6字节,设备地址1字节,工作模式1字节
		bootInfo.setDevCode(t.getData()[6] & 0xFF); // byte转为无符号int
		bootInfo.setWorkMode(t.getData()[7]);
		
		MQMessageOfHR msg = new MQMessageOfHR();
		msg.setActioncode(ACTION_CODE);
		msg.setAwsPostdata(bootInfo);

		// 发送开机信息到MQ, 资产监听
		String json = JSON.toJSONString(msg);
		topicSender.send("hrReader", json);
		logger.info("HR设备发送【开机信息】成功! ip={}, topic=hrReader, 数据={}", devIp, json);
		return null;
	}
}
